package com.huanbao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.dto.PersonalInfoDTO;
import com.huanbao.base.dto.VolunteerApplyDTO;
import com.huanbao.base.lang.Result;
import com.huanbao.entity.*;
import com.huanbao.service.*;
import com.huanbao.util.ShiroUtil;
import com.huanbao.vo.PersonalIntegralDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 个人中心 前端控制器
 * @author: ZQ
 * @date: 2021-04-27-10:14
 */

@Slf4j
@RestController
@RequestMapping("/personal")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PersonalCenterController {

    private final PersonalIntegralNumberService integralNumberService;

    private final PersonalMessageService messageService;

    private final PersonalNotificationService notificationService;

    private final PersonalTaskService taskService;

    private final PersonalIntegralDetailService integralDetailService;

    private final VolunteerApplyService volunteerApplyService;

    private final PersonalService personalService;

    private final UserService userService;

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/getIntegralNumber")
    public Result getIntegralNumber() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->getIntegralNumber");
        PersonalIntegralNumber one = integralNumberService.getOne(new QueryWrapper<PersonalIntegralNumber>().eq("user_id", id));
        if (null == one) {
            return Result.success(0);
        }
        return Result.success(one.getIntegralNumber());
    }

    /**
     * asda
     * @return asd
     */
    @GetMapping("/getIntegralDetail")
    public Result getIntegralDetail() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->getIntegralDetail");
        List<PersonalIntegralDetail> list = integralDetailService.list(new QueryWrapper<PersonalIntegralDetail>().eq("user_id", id));
        List<PersonalIntegralDetailVO> voList = new ArrayList<>();
        for (PersonalIntegralDetail personalIntegralDetail : list) {
            PersonalIntegralDetailVO vo = new PersonalIntegralDetailVO();
            if (personalIntegralDetail.getType().equals(1)) {
                vo.setType("消费");
            } else {
                vo.setType("获得");
            }
            vo.setNumber(personalIntegralDetail.getNumber());
            vo.setTime(personalIntegralDetail.getCreatedDt());
            voList.add(vo);
        }
        return Result.success(voList);
    }

    @GetMapping("/getMessage")
    public Result getMessage() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->getMessage");
        List<PersonalMessage> list = messageService.list(new QueryWrapper<PersonalMessage>().eq("user_id", id));
        return Result.success(list);
    }

    @GetMapping("/getNotification")
    public Result getNotification() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->getNotification");
        List<PersonalNotification> list = notificationService.list(new QueryWrapper<PersonalNotification>().eq("user_id", id));
        return Result.success(list);
    }

    @GetMapping("/getTask")
    public Result getTask() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->getTask");
        List<PersonalTask> list = taskService.list(new QueryWrapper<PersonalTask>().eq("user_id", id).eq("state", 1));
        return Result.success(list);
    }


    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @PostMapping("/volunteer/apply")
    public Result volunteerApply(@RequestBody @Validated VolunteerApplyDTO apply) {

        Long id = ShiroUtil.getProfile().getId();

        log.info("志愿者申请 ------------>用户id为", id + "  ", apply);
        //判断是否已经申请
        VolunteerApply one = volunteerApplyService.getOne(new QueryWrapper<VolunteerApply>().eq("user_id", id).eq("deleted", 0));
        //状态为2说明申请未通过,可以再次申请
        if (null != one && one.getState() != 2) {
            Integer state = one.getState();
            String message = null;
            switch (state) {
                case 0:
                    message = "正在审批，";
                    break;
                case 1:
                    message = "已审批通过，";
                    break;
                default:
                    break;
            }
            return Result.fail("您已申请，状态为" + message + "请勿重复申请。");
        }
        String message = "您于" + LocalDateTime.now().format(formatter) + "申请成功志愿者，状态为正在审批。";
        userService.createMessage(message, id);
        List<String> reason = apply.getReason();
        StringBuilder str = new StringBuilder();
        for (String s : reason) {
            str.append(s).append(",");
        }

        VolunteerApply volunteerApply = new VolunteerApply();
        volunteerApply.setUserId(id);
        volunteerApply.setCompellation(apply.getCompellation());
        volunteerApply.setTelephone(apply.getTelephone());
        volunteerApply.setClassAndGrade(apply.getClassAndGrade());
        volunteerApply.setArea(apply.getArea());
        volunteerApply.setReason(str.toString());
        boolean save = volunteerApplyService.save(volunteerApply);
        return Result.success(save);

    }

    @GetMapping("/info")
    public Result personalInfo() {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->personalInfo");
        User user = userService.getById(id);
        return Result.success(user);
    }

    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestBody MultipartFile param){
        return Result.success(null);
    }

    @PostMapping("/info/modify")
    public Result personalInfoModify(@RequestBody @Validated PersonalInfoDTO info) {
        Long id = ShiroUtil.getProfile().getId();
        log.info(id + "------------------->personalInfoModify");
        User user = userService.getById(id);
        user.setName(info.getName());
        user.setAddress(info.getAddress());
        user.setTelephone(info.getTelephone());
        user.setArea(info.getArea());
        userService.updateById(user);
        return Result.success(user);
    }

}
